package com.spring.http.basic.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 开发公司：个人
 * 版权：个人
 * <p>
 * MainFilter
 *
 * @author 刘志强
 * @WebFilter(filterName = "mainFilter", urlPatterns = {"/*"})
 * filterName 过滤器名称 urlPatterns 需要过滤的url
 * @created Create Time: 2019/5/25
 */

@WebFilter(filterName = "realm1Filter", urlPatterns = {"/realm1/*"})
@Slf4j
public class MainFilter implements Filter {

    public final static String USERNAME = "admin";
    public final static String PASSWORD = "123456";
    public static final String BASIC_ = "Basic ";


    @Override
    public void init(FilterConfig filterConfig) {
        log.info("过滤器创建");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        log.info("执行过滤请求:{}", request.getRequestURI());

        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            response.setStatus(401);
            response.setHeader("www-Authenticate", "Basic realm='realm1' charset='utf-8'");
        } else {
            String base64Str = Base64Utils.encodeToString((USERNAME + ":" + PASSWORD).getBytes("UTF-8"));
            if (!StringUtils.equals(authorization.replaceAll(BASIC_, ""), base64Str)) {
                response.setStatus(401);
                response.setHeader("www-Authenticate", "Basic realm='realm1' charset='utf-8'");
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        log.info("过滤器销毁");
    }
}